package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * * @title: UserController
 *
 * @Author Philcan
 * @Date: 2021/8/5 18:30
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {
        try {
            String phone = param.get("phone");
            String code = param.get("verification");
            String data = this.userService.login(phone, code);
            if (StringUtils.isNoneEmpty(data)) {
                Map<String, Object> result = new HashMap<>(2);
                String[] split = StringUtils.split(data, "|");
                result.put("token", split[0]);
                result.put("isNew", Boolean.valueOf(split[1]));
                return ResponseEntity.ok(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登陆失败").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    @GetMapping("{token}")
    public User queryUserByToken(String token) {
        return this.userService.queryUserByToken(token);
    }
}
